#encoding:utf-8

from django.http import HttpResponse,HttpResponseRedirect
from django.core.paginator import PageNotAnInteger, Paginator, InvalidPage, EmptyPage
from django.core.urlresolvers import reverse
from django.shortcuts import render
from django.http import Http404
from courses.models import Types,Tiny_type,Course,Lession,Course_comment
from login.models import Register
from users.models import Info,Teacher,News,Review_of_news,Message,Follow_topic,Follow_user,Follow_group,Follow_course,Post_reward,Post_course,Purchase,Good_news,Good_review_of_news,Warning_mes
from rewards.models import Reward,Uncover,Reward_mes,Reward_course,Reward_lession
from django.utils import timezone 
from PIL import Image
from django.contrib import messages
import re,md5,os,time,qiniu.io,qiniu.conf,qiniu.rs,base64,math
from tasks import deal_vedio
from remind import warn


#CUR_PATH = 'E:/Demo/'
CUR_PATH = '/var/www/html/'

class PutPolicy(object):
    scope = 'maizhi'
    expires = 3600
    callbackUrl = None
    callbackBody = None
    returnUrl = None
    returnBody = None
    endUser = None
    asyncOps = None

    def __init__(self, scope):
        self.scope = scope

qiniu.conf.ACCESS_KEY = "EW8idy4EFnJDBicDJZhPIVIVDU9AL0g4waW5MNtJ"
qiniu.conf.SECRET_KEY = "C1qaP_-sgjVgQb6GGHJ-vCle0qTiGI8qtbgOumOB"

#课程的大分类
def types(request):
    """通用:判断是否已经登入，否则退出到登入页面"""
    if not 'id' in request.session:
        return HttpResponseRedirect(reverse('login:index'))
    """通用: 获取个人信息"""
    info=Info.objects.get(user_id=request.session['id'])
    types=Types.objects.all()
    #根据购买量从数据库获取前20条
    course=Course.objects.all().order_by('-purchase_con')[0:20]
    #除去用户已经购买的课程
    c=Follow_course.objects.filter(user_id=request.session['id'])
    follow=[]
    courses=[]
    for j in c:
        follow.append(j.follow_course_id)
    for i in course:
        if i.id in follow:
            pass
        else:
            each=[]
            each.append(i.domain)		#0
            each.append(i.img)		#1
            each.append(i.id)		#2
            each.append(i.name)		#3
            courses.append(each)
    """通用:获取用户的私信以及提醒"""
    waningMes=warn(request.session['id'])[0]
    havent=warn(request.session['id'])[1]
    mess=warn(request.session['id'])[2]
    """通用:输出到模板"""
    return render(request,'courses/types.html',{'info':info,'message':mess,'havent':havent,'waningMes':waningMes,'types':types,'courses1':courses[0:4],'courses2':courses[5:9],'courses3':courses[10:14],'message':mess})

#大分类下的小分类
def tinytypes(request,ty):
    if not 'id' in request.session:
        return HttpResponseRedirect(reverse('login:index'))
    tiny=Tiny_type.objects.filter(types_id=int(ty))
    types=Types.objects.get(id=int(ty))
    info=Info.objects.get(user_id=request.session['id'])
    waningMes=warn(request.session['id'])[0]
    havent=warn(request.session['id'])[1]
    mess=warn(request.session['id'])[2]
    return render(request,'courses/tinyTypes.html',{'info':info,'tiny':tiny,'types':types,'waningMes':waningMes,'havent':havent,'message':mess})

#某一小分类下的课程列表
def courselist(request,id):
    if not 'id' in request.session:
        return HttpResponseRedirect(reverse('login:index'))

    #根据条件检索时，1：根据价格排序，2：根据时间排序，3：根据评价排序
    sel=int(1)
    if 'sel' in request.GET:
        sel=int(request.GET['sel'])
    if sel==1:
        course=Course.objects.filter(tiny_type_id=id).order_by('price')
    elif sel==2:
        course=Course.objects.filter(tiny_type_id=id).order_by('-time')
    elif sel==3:
        course=Course.objects.filter(tiny_type_id=id).order_by('grade')


    info=Info.objects.get(user_id=request.session['id'])
    tiny=Tiny_type.objects.get(id=id)
    types=Types.objects.get(id=tiny.types_id)
    #Django的分页类,设置每页15条,如果输入的页数大于总页数则返回至第一页
    limit = 15
    paginator = Paginator(course, limit)
    page = request.GET.get('page')
    try:
        course = paginator.page(page)
    except PageNotAnInteger:
        course = paginator.page(1)
    except EmptyPage:
        course = paginator.page(paginator.num_pages)
    #将结果以result列表保存
    result=[]
    for i in course:
        each=[]
        each.append(i.img)			#0
        each.append(i.name)			#1
        each.append(i.introduce)	#2
        each.append(i.price)		#3
        k=Info.objects.get(user_id=i.teacher_id)
        each.append(k.user_name)	#4
        each.append(i.id) 			#5
        each.append(i.grade) 		#6
        each.append(i.grade_con)	#7
        each.append(i.purchase_con)	#8
        each.append(i.domain)		#9
        result.append(each)
    #推荐的发布者,按照课程的售出量排序
    courses=Course.objects.filter(tiny_type_id=id).order_by('-purchase_con')
    users=[]
    recommend=[]
    #将users唯一化
    for j in courses:
        users.append(j.teacher_id)
    users.sort()
    x=0
    while x<len(users) :
        if int(users[x]) == int(users[x-1]) :
            users.remove(users[x])
        else :
            x+=1
    #获取推荐的发布者的资料,并且以recommend列表存储
    for u in users:
        each=[]
        k=Info.objects.get(user_id=u)
        each.append(k.user_name)		#0
        each.append(k.domain)		#1
        each.append(k.img)			#2
        each.append(k.sign)			#3
        each.append(u)			#4
        each.append(u)	#5
        recommend.append(each)
    waningMes=warn(request.session['id'])[0]
    havent=warn(request.session['id'])[1]
    mess=warn(request.session['id'])[2]
    return render(request,'courses/courseList.html',{'sel':sel,'info':info,'message':mess,'havent':havent,'waningMes':waningMes,'course':course,'tiny':tiny,'types':types,'result':result,'user1':recommend[0:3],'user2':recommend[4:6]})

#创建课程。如果时发布者权限，则直接可以发布,分为悬赏的课程和普通的课程；如果没有发布者权限则需要申请权限。通过try，except实现
def coursecreate(request):
    if not 'id' in request.session:
        return HttpResponseRedirect(reverse('login:index'))
    try:
        tj=time.time()
        #七牛
        policy = qiniu.rs.PutPolicy('mzvideoimg')
        uptoken = policy.token()
        #图片上传与图片的剪裁,图片切割的四个坐标通过ajax传递过来
        if 'picture' in request.FILES:
            image=request.FILES['picture']
            #获取图片的拓展名
            suffix=image.name.split('.')[-1]
            #Python的Image图片操作库
            image=Image.open(image)
            (x,y)=image.size
            x_s=330
            y_s=y*x_s/x
            little_img = image.resize((x_s,y_s),Image.ANTIALIAS)
            coordinate=request.POST['coordinate'].split('*')
            region = (int(round(float(coordinate[0]))+1),int(coordinate[1]),int(coordinate[2]),int(coordinate[3]))
            #region=(0,0,100,100)
            cropImg = little_img.crop(region)
            #cropImg=pic.thumbnail((int(coordinate[2]),int(coordinate[3])),Image.ANTIALIAS)

            #先将图片保存到本地
            cropImg.save(CUR_PATH + r"templates/picture/course/"+str(tj)+'.'+suffix)
            #pic.save("/home/tron/Maizhi/templates/picture/course/"+str(tj)+'.'+suffix,suffix)
            #dirs ='templates/picture/course/'+str(tj)
            #if os.path.isfile(dirs):
            #	os.remove(dirs)
            #fp=open(dirs, 'wb')
            #content=pic.read()
            #fp.write(content)
            #fp.flush()
            #fp.close()
        domain='http://mzvideoimg.qiniudn.com'
        #悬赏的课程处
        if 'user' in request.POST:
            reward=Reward.objects.get(id=request.POST['reward'])
            #判断用户的合法性
            if int(request.session['id']) != int(request.POST['user']):
                raise Http404
            deadline_str=str(timezone.now())
            course_list=deadline_str.split('.')
            deadline_str=course_list[0]
            timeArray=time.strptime(deadline_str,"%Y-%m-%d %H:%M:%S")
            timeStamp=int(time.mktime(timeArray))
            x = time.localtime(timeStamp+2592000)
            deadline=time.strftime('%Y-%m-%d %H:%M:%S',x)
            course=Reward_course(reward_id=request.POST['reward'],name=request.POST['name'],img=str(tj),domain=domain,introduce=request.POST['introduce'],password=int(request.POST['password']),price=int(reward.price),teacher_id=int(request.POST['user']),to_id=int(request.POST['to']),deadline=deadline)
            course.save()
            the_course=Reward_course.objects.get(id=course.id)
            the_course.deadline=deadline
            the_course.save()
            reward.course_id=course.id
            #设置课程的权限
            reward.status=1
            reward.save()
            #回调时使用
            method='1'
        #普通课程处
        else:
            deadline_str=str(timezone.now())
            course_list=deadline_str.split('.')
            deadline_str=course_list[0]
            timeArray=time.strptime(deadline_str,"%Y-%m-%d %H:%M:%S")
            timeStamp=int(time.mktime(timeArray))
            x = time.localtime(timeStamp+2592000)
            deadline=time.strftime('%Y-%m-%d %H:%M:%S',x)
            course=Course(name=request.POST['name'],img=str(tj),domain=domain,introduce=request.POST['introduce'],tiny_type_id=request.POST['tiny'],price=int(request.POST['price']),status=0,over=0,teacher_id=int(request.session['id']),grade=0,deadline=deadline)
            method='0'
            course.save()
            the_course=Course.objects.get(id=course.id)
            the_course.deadline=deadline
            the_course.save()
            user_id=int(request.session['id'])
            #将动态添加到个人的新鲜事
            content='发布了课程<a href="/courses/types/tiny/course/lession/'+str(course.id)+'">'+str(request.POST['name'])+'</a>'
            news=News(user_id=user_id,content=content,good_con=0,share_con=0,review_con=0)
            news.save()
        #七牛
        qiniu.io.put_file(uptoken,str(tj),CUR_PATH + r"templates/picture/course/"+str(tj)+'.'+suffix)
        status=course.id
        #记录用户发布的所有课程系列
        Post_course(user_id=request.session['id'],post_course_id=course.id,status=1).save()
        #return HttpResponseRedirect('../types/tiny/course/lession/'+str(course.id))
        return render(request,'courses/wait.html',{'status':status,'method':method,'course':course})
        #return HttpResponse(str(int(round(float(coordinate[0]))+1))+"---"+str(int(coordinate[1]))+"---"+str(int(coordinate[2]))+"---"+str(int(coordinate[3])))
        #return HttpResponse(coordinate)
    #非发布者权限处
    except:
        info=Info.objects.get(user_id=request.session['id'])
        #申请发布者权限
        if int(request.session['status'])==1:
            return render(request,'users/teacherApply.html',{'info':info})
        tag=Types.objects.all()
        #记录我发布的所有课程数
        mycourse=Course.objects.filter(teacher_id=request.session['id']).count()
        #是否是悬赏的课程
        if 'method' in request.GET:
            reward=Reward.objects.get(id=base64.decodestring(request.GET['reward']))
            method='1'
            price=int(reward.price)
            #加密，防止被篡改
            user=base64.decodestring(request.GET['user'])
            reward=base64.decodestring(request.GET['reward'])
            to=base64.decodestring(request.GET['to'])
        else:
            method='0'
            price=''
            user=''
            reward=""
            to=""
        waningMes=warn(request.session['id'])[0]
        havent=warn(request.session['id'])[1]
        mess=warn(request.session['id'])[2]
        return render(request,'courses/courseCreate.html',{'to':to,'reward':reward,'waningMes':waningMes,'user':user,'message':mess,'havent':havent,'tag':tag,'info':info,'mycourse':mycourse,'method':method,'price':price})

#创建课程时的级联下拉菜单，获取小分类
def gettiny(request):
    alltiny=Tiny_type.objects.filter(types_id=request.GET['tiny'])
    tiny=[]
    for i in alltiny:
        tiny.append(i.name)
        tiny.append('*')
        tiny.append(i.id)
        tiny.append(',')
    tiny.pop()
    return HttpResponse(tiny)

#修改课程信息：课程名，课程简介,ajax通过回调的1，2来判断操作是否成功
def changes(request):
    try:
        course=Course.objects.get(id=request.GET['courseid'])
        if 'name' in request.GET:
            course.name=request.GET['name']
        elif 'intro' in request.GET:
            course.introduce=request.GET['intro']
        course.save()
        return HttpResponse('1')
    except:
        return HttpResponse('2')

#完结课程系列，不可逆.ajax通过回调的1，2来判断操作是否成功
def finish(request):
    try:
        if int(request.GET['method'])==1:
            course=Reward_course.objects.get(id=request.GET['course'])
            course.over=1
            course.save()
            reward_id=course.reward_id
            to=course.to_id
            warning_mesTable=Warning_mes(from_id=int(request.session['id']),to=int(to),aim_id=int(reward_id),status=7)
            #warning_mesTable=Warning_mes(from_id=1,to=1,aim_id=1,status=7)
            warning_mesTable.save()
        elif int(request.GET['method'])==0:
            course=Course.objects.get(id=request.GET['course'])
            course.over=1
            course.save()
        return HttpResponse(1)
    except:
        return HttpResponse(2)

#悬赏课程，验证输入的密码是否正确
def auth(request,id):
    if not 'id' in request.session:
        return HttpResponseRedirect(reverse('login:index'))
    try:
        reward=Reward_course.objects.get(id=id)
        #密码正确
        if int(request.GET['pwd'])==int(reward.password):
            return HttpResponseRedirect("/courses/types/tiny/course/lession/"+str(reward.id)+"?method=1")
        #密码错误
        else:
            return HttpResponse('密码错误！')
    except:
        reward=Reward_course.objects.get(id=id)
        waningMes=warn(request.session['id'])[0]
        havent=warn(request.session['id'])[1]
        mess=warn(request.session['id'])[2]
        return render(request,'rewards/auth.html',{'reward':reward,'waningMes':waningMes,'havent':havent,'message':mess})

#某一系列课程的所有课时，以及课程的评价，发布者信息等等
def thecourse(request,id):
    if not 'id' in request.session:
        return HttpResponseRedirect(reverse('login:index'))
    #判断是否是悬赏课程
    if 'method' in request.GET:
        course=Reward_course.objects.get(id=id)
        info=Info.objects.get(user_id=request.session['id'])
        tinfo=Info.objects.get(user_id=course.teacher_id)
        price="悬赏课程"
        #判断课程的所有权,1:自己,2:已购买,3:未付款,4:未购买.
        if course.teacher_id==request.session['id']:
            limit='1'
        else:
            user=Purchase.objects.filter(user_id=request.session['id']).filter(status=1)
            own=[]
            for u in user:
                own.append(u.purchase_id)
            if course.id in own:
                limit='2'
            else:
                nopay=Purchase.objects.filter(user_id=request.session['id']).filter(status=2)
                nopaid=[]
                for n in nopay:
                    nopaid.append(n.purchase_id)
                if course.id in nopaid:
                    limit='3'
                else:
                    limit='4'
        lessions=Reward_lession.objects.filter(course_id=course.id)
        s=1
        waningMes=warn(request.session['id'])[0]
        havent=warn(request.session['id'])[1]
        mess=warn(request.session['id'])[2]
        return render(request,'courses/theCourse.html',{'s':s,'info':info,'waningMes':waningMes,'havent':havent,'tinfo':tinfo,'course':course,'price':price,'limit':limit,'lession':lessions,'message':mess})
    #普通课程处
    else:
        info=Info.objects.get(user_id=request.session['id'])
        course=Course.objects.get(id=id)
        tiny=Tiny_type.objects.get(id=course.tiny_type_id)
        types=Types.objects.get(id=tiny.types_id)
        tinfo=Info.objects.get(user_id=course.teacher_id)
        f=Follow_user.objects.filter(user_id=request.session['id'])
        #是否关注发布者,1:已关注,2:未关注,3:自己
        follow=[]
        for i in f:
            follow.append(i.follow_user_id)
        if request.session['id']==course.teacher_id:
            focus='3'
        elif course.teacher_id in follow:
            focus='1'
        else:
            focus='0'
        #判断是否有权限操作课程,1:课程所有者,2:已购买,3:未付款,4:未购买
        if course.teacher_id==request.session['id']:
            limit='1'
        else:
            user=Purchase.objects.filter(user_id=request.session['id']).filter(status=1)
            own=[]
            for u in user:
                own.append(u.purchase_id)
            if course.id in own:
                limit='2'
            else:
                nopay=Purchase.objects.filter(user_id=request.session['id']).filter(status=2)
                nopaid=[]
                for n in nopay:
                    nopaid.append(n.purchase_id)
                if course.id in nopaid:
                    limit='3'
                else:
                    limit='4'
        #课程系列的评论
        comment=Course_comment.objects.filter(user_id=request.session['id']).filter(course_id=course.id)
        #判断是否已经评价
        if comment:
            review='1'
        else:
            review='0'
        #所有的课程评论
        dis=Course_comment.objects.filter(course_id=course.id)
        discuss=[]
        for d in dis:
            each=[]
            i=Info.objects.get(user_id=d.user_id)
            each.append(i.user_name)      			 #0
            each.append(i.img)			 	 #1
            each.append(d.content)			 #2
            each.append(d.grade)				 #3
            each.append(d.time)				 #4
            each.append(d.id)				 #5
            each.append(i.domain)				 #6
            each.append(i.user_id)				 #7
            discuss.append(each)
        #获取课程系列的所有课时
        lessions=Lession.objects.filter(course_id=course.id)
        #messages.success(request, 'Hello world.')
        #判断发布者权限,purview=1:普通发布者,purview=2：企业用户
        purview=''
        if int(request.session['status'])==int(2):
            purview='1'
        elif int(request.session['status'])==int(3):
            purview='2'
        fc=Follow_course.objects.filter(user_id=request.session['id']).filter(follow_course_id=course.id)
        #是否已经收藏课程,collect=1:已收藏,collect=2:未收藏
        collect=''
        if fc:
            collect='1'
        else:
            collect='2'
        s=0
        waningMes=warn(request.session['id'])[0]
        havent=warn(request.session['id'])[1]
        mess=warn(request.session['id'])[2]
        return render(request,'courses/theCourse.html',{'s':s,'info':info,'waningMes':waningMes,'havent':havent,'course':course,'tinfo':tinfo,'limit':limit,'tiny':tiny,'type':types,'focus':focus,'lession':lessions,'discuss':discuss,'review':review,'purview':purview,'collect':collect,'message':mess,'c_id':id})

#课程购买

"""因为没有连接支付宝，purchses表中的status支付成功是1，未支付是0."""

def purchase(request,id):
    if not 'id' in request.session:
        return HttpResponseRedirect(reverse('login:index'))
    course=Course.objects.get(id=id)
    user=Info.objects.get(user_id=course.teacher_id)
    info=Info.objects.get(user_id=request.session['id'])
    waningMes=warn(request.session['id'])[0]
    havent=warn(request.session['id'])[1]
    mess=warn(request.session['id'])[2]
    return render(request,'courses/purchase.html',{'info':info,'course':course,'user':user,'waningMes':waningMes,'havent':havent,'message':mess})

#添加课时
def addlession(request,id):
    if not 'id' in request.session:
        return HttpResponseRedirect(reverse('login:index'))

    suffixdoc = ''
    try:
        info=Info.objects.get(user_id=request.session['id'])
        #判断是悬赏课程还是普通课程,request.POST['method']=1:悬赏,request.POST['method']=2:普通
        if  request.POST['method']=='1':
            course=Reward_course.objects.get(id=id)
            #如果有课程文档的话
            if 'lessiondoc' in request.FILES:
                policy = qiniu.rs.PutPolicy('mzvideodoc')
                uptoken = policy.token()
                #doc=request.FILES['lessiondoc'].name
                doc=time.time()
                suffixdoc=request.FILES['lessiondoc'].name.split('.')[-1]
                dirs ='templates/doc/'+str(doc)+'.'+suffixdoc
                content = request.FILES['lessiondoc'].read()
                if os.path.isfile(dirs):
                    os.remove(dirs)
                fp=open(dirs, 'wb')
                fp.write(content)
                fp.flush()
                fp.close()
                qiniu.io.put_file(uptoken,str(doc)+'.'+suffixdoc,CUR_PATH + r"templates/doc/"+str(doc)+'.'+suffixdoc)
            #如果无课程文档的话
            else:
                doc=''
            if 'lessionvideo' in request.FILES:
                policy = qiniu.rs.PutPolicy('mzvideo')
                uptoken = policy.token()
                #video=request.FILES['lessiondoc'].name
                video=time.time()
                suffix=request.FILES['lessionvideo'].name.split('.')[-1]
                dirs ='templates/video/'+str(video)+'.'+suffix
                content = request.FILES['lessionvideo'].read()
                if os.path.isfile(dirs):
                    os.remove(dirs)
                fp=open(dirs, 'wb')
                fp.write(content)
                fp.flush()
                fp.close()
                deal_vedio(str(video), suffix)
                qiniu.io.put_file(uptoken, str(video) + '.flv', CUR_PATH + r"templates/video/" + str(video) + '.flv')
                #qiniu.io.put_file(uptoken,str(video)+'_full.flv',CUR_PATH + r"templates/video/"+str(video)+'_full.flv')
            else:
                video=''
            domaindoc="http://mzvideodoc.qiniudn.com"
            domainvideo="http://mzvideo.qiniudn.com"
            result=Reward_lession(course_id=id,name=request.POST['lessionname'],video=domainvideo+str(video)+'.'+suffix,doc=domaindoc+str(doc)+'.'+suffix,lession_no=request.POST['lessionid'])
            result.save()
            return render(request,'courses/wait.html',{'info':info,'course':course,'result':result.id,'method':'1'})
        #普通课程
        else:
            course=Course.objects.get(id=id)
            if 'lessiondoc' in request.FILES:
                policy = qiniu.rs.PutPolicy('mzvideodoc')
                uptoken = policy.token()
                #doc=request.FILES['lessiondoc'].name
                doc=time.time()
                suffixdoc=request.FILES['lessiondoc'].name.split('.')[-1]
                dirs ='templates/doc/'+str(doc)+'.'+suffixdoc
                content = request.FILES['lessiondoc'].read()
                if os.path.isfile(dirs):
                    os.remove(dirs)
                fp=open(dirs, 'wb')
                fp.write(content)
                fp.flush()
                fp.close()
                qiniu.io.put_file(uptoken,str(doc)+'.'+suffixdoc,CUR_PATH + r"templates/doc/"+str(doc)+'.'+suffixdoc)
            else:
                doc=''
            if 'lessionvideo' in request.FILES:
                policy = qiniu.rs.PutPolicy('mzvideo')
                uptoken = policy.token()
                #video=request.FILES['lessiondoc'].name
                video=time.time()
                suffix=request.FILES['lessionvideo'].name.split('.')[-1]
                dirs ='templates/video/'+str(video)+'.'+suffix
                content = request.FILES['lessionvideo'].read()
                if os.path.isfile(dirs):
                    os.remove(dirs)
                fp=open(dirs, 'wb')
                fp.write(content)
                fp.flush()
                fp.close()
                deal_vedio(str(video),suffix)
                qiniu.io.put_file(uptoken,str(video)+'.flv',CUR_PATH + r"templates/video/"+str(video)+'.flv')
            else:
                video=''
        domaindoc="http://mzvideodoc.qiniudn.com/"
        domainvideo="http://mzvideo.qiniudn.com/"
        result=Lession(course_id=id,name=request.POST['lessionname'],video=domainvideo+str(video)+'.flv',doc=domaindoc+str(doc)+'.'+suffixdoc,lession_no=request.POST['lessionid'])
        result.save()

        courseName=Course.objects.get(id=id).name
        user_id=int(request.session['id'])
        #添加到用户的新鲜事里面
        content='在课程<a href="/courses/types/tiny/course/lession/'+str(id)+'">'+str(courseName)+'</a>中发布了新课时: '+str(request.POST['lessionname'])
        news=News(user_id=user_id,content=content,good_con=0,share_con=0,review_con=0)
        news.save()
        return render(request,'courses/wait.html',{'info':info,'course':course,'result':result.id,'method':'0'})
    #页面显示
    except Exception as e:
        info=Info.objects.get(user_id=request.session['id'])
        if "method" in request.GET:
            course=Reward_course.objects.get(id=id)
            method='1'
        else:
            course=Course.objects.get(id=id)
            method='0'
        waningMes=warn(request.session['id'])[0]
        havent=warn(request.session['id'])[1]
        mess=warn(request.session['id'])[2]
        err = '错误：' + e.message
        return render(request,'courses/addLession.html',
                      {'info':info,'waningMes':waningMes,'havent':havent,'message':mess,'course':course,'method':method, 'err': err})

#课程购买的后台	
def buy(request,cid):
    if not 'id' in request.session:
        return HttpResponseRedirect(reverse('login:index'))
    course=Course.objects.get(id=cid)
    info=Info.objects.get(user_id=request.session['id'])
    #彩蛋
    if float(request.GET['price'])!=float(course.price):
        return HttpResponse('碧池，滚粗！！！！')
    else:
        if Purchase.objects.filter(purchase_id=cid).filter(user_id=request.session['id']) :
            return HttpResponse("课程已经购买！")
        else :
            Purchase(user_id=request.session['id'],purchase_id=cid,teacher_id=course.teacher_id,status=1).save()
            con=int(course.purchase_con)+int(1)
            course.purchase_con=con
            course.save()
            return render(request,'courses/wait.html',{'id':course.id,'info':info})

#课程评论的后台
def comment(request):
    course_comment_table=Course_comment(user_id=request.session['id'],course_id=request.GET['course'],content=request.GET['content'],grade=request.GET['star'])
    course_comment_table.save()
    to=Course.objects.get(id=request.GET['course']).teacher_id
    info=Info.objects.get(user_id=request.session['id'])
    name=str(info.user_name)
    img=str(info.img)
    warning_mesTable=Warning_mes(from_id=int(request.session['id']),to=int(to),aim_id=request.GET['course'],status=10,review_id=int(course_comment_table.id))
    warning_mesTable.save()
    #name，img便于ajax页面输出
    return HttpResponse('1,'+name+','+img)

#课程收藏后台
def collect(request):
    Follow_course(user_id=request.session['id'],follow_course_id=request.GET['course']).save()
    return HttpResponse('1')

#课程的图片更新
def update(request,id):
    if not 'id' in request.session:
        return HttpResponseRedirect(reverse('login:index'))
    course=Course.objects.get(id=id)
    if 'courseImg' in request.FILES:
        image=request.FILES['courseImg']
        filename=course.img
        dirs ='templates/picture/course/'+str(filename)
        content = image.read()
        if os.path.isfile(dirs):
            os.remove(dirs)
        fp=open(dirs, 'wb')
        fp.write(content)
        fp.flush()
        fp.close()
        course.img=str(filename)
        course.save()
        return render(request,'courses/wait.html',{'id':course.id})
    else:
        return HttpResponse('1')

#pdf阅读器
def viewer(request,lessionid):
    if not 'id' in request.session:
        return HttpResponseRedirect(reverse('login:index'))
    lession=Lession.objects.get(id=lessionid)
    return render(request,"courses/viewer.html",{'lession':lession})

#视频播放
def play(request,id):
    if not 'id' in request.session:
        return HttpResponseRedirect(reverse('login:index'))
    try:
        lession=Lession.objects.get(id=id)
        course=Course.objects.get(id=lession.course_id)
        tiny=Tiny_type.objects.get(id=course.tiny_type_id)
        types=Types.objects.get(id=tiny.types_id)
        info=Info.objects.get(user_id=course.teacher_id)
        #非发布者的系列学习进度
        if request.session['id']!=course.teacher_id:
            past=Purchase.objects.filter(user_id=request.session['id']).get(purchase_id=course.id)
            if past.process=="":
                past.process=str(past.process)+str(lession.id)
            else:
                #lists=past.process.split(',')
                lists=list(past.process)
                if str(lession.id) in lists:
                    pass
                else:
                    past.process=str(past.process)+str(lession.id)
            past.save()
        else:
            past=""
        #判断发布者权限,purview=1:普通发布者,purview=2：企业用户
        purview=''
        if int(request.session['status'])==int(2):
            purview='1'
        elif int(request.session['status'])==int(3):
            purview='2'

        f=Follow_user.objects.filter(user_id=request.session['id'])
        follow=[]
        #是否关注发布者,1:已关注,0:未关注,3:自己
        for i in f:
            follow.append(i.follow_user_id)
        if request.session['id']==course.teacher_id:
            focus='3'
        elif course.teacher_id in follow:
            focus='1'
        else:
            focus='0'
        #全部课时的列表
        lessions=Lession.objects.filter(course_id=course.id)
        if request.session['id']!=course.teacher_id:
            studied=Purchase.objects.filter(user_id=request.session['id']).get(purchase_id=course.id)
            studied=list(studied.process)
            alllessions=[]
            for j in lessions:
                each=[]
                if j.id in studied:
                    each.append(1)
                else:
                    each.append(0)
                each.append(j.name)
                each.append(studied)
                alllessions.append(each)
        else:
            alllessions=lessions
        waningMes=warn(request.session['id'])[0]
        havent=warn(request.session['id'])[1]
        mess=warn(request.session['id'])[2]
        return render(request,'courses/player.html',{'lession':lession,'waningMes':waningMes,'havent':havent,'course':course,'tiny':tiny,'types':types,'info':info,'purview':purview,'focus':focus,'alllessions':alllessions,'message':mess})
    except:
        return HttpResponse("请先购买课程！！！！")
